const WebSocket = require('ws');
const axios = require('axios');
const nodemailer = require('nodemailer');
const http = require('http');

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('WebSocket Server Running\n');
});

// 创建WebSocket服务器，附加到HTTP服务器上
const wss = new WebSocket.Server({ server });
let isMeasuring = false;
let measurementInterval;
let alertConfig = null; // 存储警报配置

// 准备邮箱的配置
const transporter = nodemailer.createTransport({
    host: 'smtp.163.com',
    port: 465,
    secure: true,
    auth: {
        user: '填写你的邮箱',
        pass: '填写你申请的密码'
    }
});

// 发送邮箱
async function sendEmail(emailAddress, distance) {
    try {
        // await transporter.sendMail({
        //     from: '填写你的邮箱',
        //     to: emailAddress,
        //     subject: '距离警报',
        //     text: `检测到异常距离：${distance}cm`,
        //     html: `<p>检测到异常距离：<strong>${distance}cm</strong></p>`
        // });
        // console.log('Alert email sent successfully');
        return true;
    } catch (error) {
        console.error('Error sending email:', error.message);
        return false;
    }
}

// 获取角度和距离参数
function parseMessage(msg) {
    const parts = msg.split('#');
    if (parts.length >= 3) {
        const distance = parseInt(parts[1]);
        const angle = parseInt(parts[2]);
        return [distance, angle];
    }
    return null;
}

// 调用函数获取角度和距离
async function fetchDistanceData() {
    try {
        const response = await axios.get('https://apis.bemfa.com/va/getmsg', {
            params: {
                uid: '填写你要访问的设备',
                topic: '填写你要访问的TCP设备云',
                type: 3,
                num: 1
            }
        });

        if (response.data.code === 0 && response.data.data.length > 0) {
            const measurement = parseMessage(response.data.data[0].msg);
            if (measurement) {
                const [distance, angle] = measurement;
                // 只返回32cm以内的测量结果
                if (distance <= 32) {
                    console.log('Valid measurement:', measurement);
                    // 检查是否需要发送警报邮件
                    if (alertConfig && distance > alertConfig.distance) {
                        console.log('Distance exceeds alert threshold, sending email...');
                        const emailSent = await sendEmail(alertConfig.email, distance);
                        if (emailSent) {
                            alertConfig = null; // 发送成功后清除警报配置
                        }
                    }
                    return measurement;
                } else {
                    console.log('Distance out of range:', distance);
                    return null;
                }
            }
        }
        return null;
    } catch (error) {
        console.error('Error fetching distance data:', error.message);
        return null;
    }
}

// websocket连接发送
wss.on('connection', (ws, req) => {
    const clientIp = req.socket.remoteAddress;
    console.log(`New client connected from ${clientIp}`);

    ws.on('message', async (message) => {
        try {
            const data = JSON.parse(message);
            
            // 保存报警的配置
            if (data.callThePolice === "1") {
                console.log('Setting up alert for distance:', data.distance);
                // 保存警报配置
                alertConfig = {
                    email: data.email,
                    distance: parseFloat(data.distance)
                };
                ws.send(JSON.stringify({
                    type: 'ALERT_CONFIG',
                    status: 'set',
                    threshold: data.distance
                }));
                return;
            }

            // 发送连接上了，双方
            if (data.command === 'ACTION') {
                console.log('Starting measurement...');
                isMeasuring = true;
                ws.send(JSON.stringify({
                    type: 'COMMAND_RESPONSE',
                    command: 'ACTION',
                    status: 'started'
                }));
                // 1秒钟执行一次
                measurementInterval = setInterval(async () => {
                    if (isMeasuring) {
                        const measurement = await fetchDistanceData();
                        if (measurement) {
                            // 发送带类型标识的数据
                            ws.send(JSON.stringify({
                                type: 'MEASUREMENT',
                                data: measurement
                            }));
                        }
                    }
                }, 1000);
            } else if (data.command === 'STOP') {
                console.log('Stopping measurement...');
                isMeasuring = false;
                if (measurementInterval) {
                    clearInterval(measurementInterval);
                }
                ws.send(JSON.stringify({
                    type: 'COMMAND_RESPONSE',
                    command: 'STOP',
                    status: 'stopped'
                }));
            }
        } catch (error) {
            console.error('Error processing message:', error.message);
            ws.send(JSON.stringify({
                type: 'ERROR',
                message: error.message
            }));
        }
    });

    ws.on('close', () => {
        console.log(`Client ${clientIp} disconnected`);
        isMeasuring = false;
        if (measurementInterval) {
            clearInterval(measurementInterval);
        }
        // 清除警报配置
        alertConfig = null;
    });
});

// 监听所有网络接口的8080端口
server.listen(8080, '0.0.0.0', () => {
    console.log('WebSocket server is running on http://0.0.0.0:8080');
    console.log('Connect from your frontend at ws://192.168.64.129:8080');
}); 